package slxy.jiangtao.dts.controller.admin;

import com.alibaba.fastjson.JSON;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.entity.sys.Role;
import slxy.jiangtao.dts.entity.sys.RoleMenu;
import slxy.jiangtao.dts.entity.sys.RoleType;
import slxy.jiangtao.dts.entity.sys.User;
import slxy.jiangtao.dts.service.sys.MenuSevice;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Code must be sexy
 * Created by Jiang Tao on 2017/4/9.
 */
@Controller
@RequestMapping("role")
public class RoleController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private CommonService commonService;
    @Autowired
    private MenuSevice menuSevice;

    @RequestMapping("index")
    public String role(ModelMap modelMap) {
        List<Role> roleList = commonService.getList(Role.class);
        Optional.ofNullable(roleList).ifPresent(
                roles ->
                        roles.forEach(
                                role -> {
                                    RoleType roleType = commonService.get(RoleType.class, Integer.parseInt(role.getType()));
                                    commonService.evict(role); //此处必须托管role,因为此时role处于持久化状态
                                    role.setType(roleType.getName());
                                }
                        ));
        modelMap.put("roleList", JSON.toJSONString(roleList));
        return "systemmanager/role";
    }

    @RequestMapping("addPage")
    public String addPage(ModelMap modelMap) {
        List<RoleType> roleTypes = commonService.getList(RoleType.class);
        modelMap.put("roleTypes", roleTypes);
        return "systemmanager/addRole";
    }

    @RequestMapping(value = "addSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult addSubmit(Role role) {
        try {
            commonService.save(role);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JSONResult.failure("添加失败");
        }
        return JSONResult.success();
    }

    @RequestMapping(value = "updateSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateSubmit(Role role) {
        try {
            commonService.updateEntity(role);
        } catch (Exception e) {
            logger.error("角色编辑失败", e);
            return JSONResult.failure("编辑失败");
        }
        return JSONResult.success();
    }

    @RequestMapping("updatePage")
    public String updatePage(Integer id, ModelMap modelMap) {
        Role role = commonService.get(Role.class, id);
        if (role != null) {
            modelMap.put("role", role);
            modelMap.put("roleTypes", JSON.toJSONString(commonService.getList(RoleType.class)));
        }
        return "systemmanager/updateRole";
    }

    @RequestMapping("delete")
    @ResponseBody
    public JSONResult delete(Integer id) {
        try {
            //删除所有相关 角色-菜单
            boolean delete = menuSevice.deleteRoleMenu(id);
            if (!delete) {
                return JSONResult.failure("删除失败");
            }
            //删除所有相关 用户-角色
            Optional.ofNullable(commonService.findByProperty(User.class, "roleId", id))
                    .ifPresent(
                            users ->
                                    users.forEach(
                                            user -> user.setRoleId(null)
                                    )
                    );

            commonService.deleteEntityById(Role.class, id);
        } catch (Exception e) {
            logger.error("角色删除失败", e);
            return JSONResult.failure("删除失败");
        }
        return JSONResult.success();
    }

    /***
     * 角色菜单权限管理页面
     * @param id 角色主键
     * @param modelMap
     * @return
     */
    @RequestMapping("roleMenuPage")
    public String showRoleMenuPage(ModelMap modelMap, @RequestParam Integer id) {
        Role role = commonService.get(Role.class, id);
        Optional.ofNullable(role).ifPresent(
                role1 -> {
                    String type = commonService.get(RoleType.class, Integer.parseInt(role1.getType())).getName();
                    commonService.evict(role1);
                    role1.setType(type);
                });
        modelMap.put("role", role);
        modelMap.put("treeNode", JSON.toJSON(menuSevice.getZtreeMenu(id)));
        return "systemmanager/roleMenu";
    }

    @RequestMapping(value = "changeRoleMenuSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult changeRoleMenuSubmit(Integer[] menus, @RequestParam Integer role) {
        try {
            menuSevice.deleteRoleMenu(role);
            if (menus != null) {
                Arrays.stream(menus).forEach(
                        menuid -> {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setMenuId(menuid);
                            roleMenu.setRoleId(role);
                            commonService.save(roleMenu);
                        });
            }
        } catch (Exception e) {
            logger.error("权限更改失败", e);
            return JSONResult.failure("权限更改失败");
        }
        return JSONResult.success();
    }

}
